package com.test.shiro.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/9/8 21:31
 */
public class SecondShiroRealm extends AuthenticatingRealm {
    public static void main(String[] args) {
        String hashAlgorithmName = "SHA1";
        Object credentials = "123456";
        ByteSource credentialsSalt = ByteSource.Util.bytes("admin");
        Object salt = credentialsSalt;
        int hashIterations = 1024;
        final SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);

        System.out.println(simpleHash);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("Second AuthenticationInfo " + token);
        // 1. 把AuthenticationToken转换为UsernamePasswordToken
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        // 2.从UsernamePasswordToken中获取username
        final String username = upToken.getUsername();
        // 3.调用数据库方法，从数据库中获取username对应的用户记录
        System.out.println("从数据库中获取username" + username + "对应的用户信息");

        // 4.若用户不存在，则可以抛出认证异常
        if ("unknown".equals(username)) {
            throw new UnknownAccountException();
        }
        // 5.根据用户信息的情况，决定是否要抛出其他的异常
        if ("monster".equals(username)) {
            throw new LockedAccountException();
        }
        // 6.根据用户的情况，来构建AuthenticationInfo对象并返回, 通常使用的实现类为SimpleAuthenticationInfo
        // 以下信息是从数据库中获取的
        //1.principal: 认证的信息，可以是username，也可以是数据表对应的实体类对象
        Object principal = username;
        //2.credentials: 密码
        Object credentials = "fc1709d0a95a6be30bc5926fdb7f22f4";
        //3. realname: 当前realm对象的name，调用父类的getName()方法即可
        String realmName = getName();
        //4. 盐值
        ByteSource credentialsSalt = ByteSource.Util.bytes(username);
        if ("admin".equals(username)) {
            credentials = "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06";
        }
        if ("user".equals(username)) {
            credentials = "073d4c3ae812935f23cb3f2a71943f49e082a718";

        }

//        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal,credentials,realmName);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
        return info;
    }
}
